package gapidt.plugin.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import gapidt.plugin.AnalysisResultsManager;

import org.apache.log4j.Logger;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;


public class AnalyzeFromMenu implements IObjectActionDelegate {
	
	static Logger logger = Logger.getLogger(AnalyzeFromMenu.class);
	
	public static final String ID = AnalyzeFromMenu.class.getCanonicalName(); 

	List<IJavaElement> selectedJavaElements = new ArrayList<IJavaElement>();

	@Override
	@SuppressWarnings("unchecked")
	public void selectionChanged(IAction action, ISelection selection) {
		selectedJavaElements.clear();
		if(selection != null){
			Iterator<Object> it = (Iterator<Object>) ((IStructuredSelection)selection).iterator();
			while(it.hasNext()){
				Object next = it.next();
				if(next instanceof IJavaElement)
					selectedJavaElements.add((IJavaElement) next);
			}
		}
	}

	@Override
	public void run(IAction action) {
		if(selectedJavaElements.size() > 0){
			AnalysisResultsManager.getInstance().clearResults();
			for(IJavaElement javaElement : selectedJavaElements)
				AnalysisResultsManager.getInstance().analyzeElement(javaElement, null);
		}else
			logger.debug("Can not perform analysis, no compilation unit selected");
	}

	@Override
	public void setActivePart(IAction arg0, IWorkbenchPart part) {
		
	}
}
